//
//  SinaPhotoView.swift
//  SinaPhotoView
//
//  Created by 冯成林 on 15/12/11.
//  Copyright © 2015年 冯成林. All rights reserved.
//

import UIKit


extension SinaPhotoView {
    
    class PhotoModel {
        
        var img: UIImage!
        var imgUrl: String!
        /** 业务模型指针 */
        var interfaceModel: AnyObject!
        init(img: UIImage!, interfaceModel: AnyObject!){self.img = img; self.interfaceModel = interfaceModel}
        init(imgUrl: String!, interfaceModel: AnyObject!){self.imgUrl = imgUrl; self.interfaceModel = interfaceModel}
    }
    
    class PhotoImgView: UIImageView {
        var photoModel: PhotoModel!
        var index: Int = 0
    }
    
    /** 朋友圈视图模式 */
    enum Model {
        
        /** 展示 */
        case Show
        
        /** 本地编辑 */
        case LocalEdit
        
        /** 网络数据编辑 */
        case NetworkEdit
    }
    
}


class SinaPhotoView: UIView {
    
    /** interface */
    var model: Model!{ didSet{ sinaPhotoViewPrepare() } }
    var addBtnClosure: (()->Void)!
    var deleteBtnClosure:(( _ i: Int,  _ interfaceModel: AnyObject?,  _ photoImageView: PhotoImgView?)->Void)!
    var maxSizeCalOutClosure:((CGSize)->Void)!
    var photoModels: [PhotoModel]! {
        get{
           if is_ShowView {return photoModels_private?.filter({$0 != nil})}
            
            let imageViews = subviews.filter({$0.isKind(of: PhotoImgView.self)}) as! [PhotoImgView]
            
            return imageViews.map({$0.photoModel})
        }
        set{
            photoModels_private = newValue;
            setNeedsLayout()
            layoutIfNeeded()
        }
    }
    var clickClosure: ((_ selectIndex: Int, _ imageView: PhotoImgView?, _ photoModel: PhotoModel?)->Void)!
    func addPhotoModels(photoModels: [PhotoModel]!){
        photoModels_private = photoModels
        photoModelsDataCommingForShow()
    }
    
    func removeALL() {
        for view: UIView in self.subviews {
            view.removeFromSuperview()
        }
    }
    
    private var is_EditView: Bool {return model != Model.Show}
    private var is_ShowView: Bool {return model == Model.Show}
    
    lazy var margin: CGFloat = 20
    lazy var colCount: CGFloat = 4
    
    var count: Int {return subviews.count}
    lazy var addBtn: UIButton = UIButton(type: UIButton.ButtonType.system)
    private var photoModels_private: [PhotoModel]! = []
    private var defaultWH: CGFloat = 0
    
    /** 展示图片回调 */
    var setImagesWithClosure:((String?,UIImageView?)->Void)!
    
    /** 是否关闭特殊的4张时的两行模式 */
    var shutOffTwoColModel_Show: Bool = false
}

extension SinaPhotoView {
    
    /** addBtn */
    private func sinaPhotoViewPrepare(){
        
        if is_EditView {
            addBtn.tintColor = .lightGray
            addBtn.setImage(UIImage(named: "SinaPhotoView.bundle/add"), for: .normal)
            addBtn.imageView?.contentMode = .scaleAspectFit
            addBtn.addTarget(self, action: #selector(clickAddBtn), for: .touchUpInside)
//            addSubview(addBtn)
            
        }else{
            for _ in 0 ..< 4 {
                addImageView(is_ShowView: true,photoModel: nil)
            }
        }
    }
    
    private func photoModelsDataCommingForShow(){
        
        for photoModel in photoModels_private {
            addImageView(is_ShowView: false, photoModel: photoModel)
        }
    }
    
    
    
    
    
    /** 点击事件 */
    @objc func clickAddBtn(){addBtnClosure?()}
    
    /** add */
    func addImageView(is_ShowView: Bool = false, photoModel: PhotoModel!){
        
        if photoModels.count >= (is_EditView ? 4 : 4) {return}
        if subviews.filter({!$0.isKind(of: UIButton.self)}).count >= 6{return}
        
        let imageView = PhotoImgView();
        imageView.isUserInteractionEnabled = true
        imageView.contentMode = .scaleAspectFill
        imageView.photoModel = photoModel
        
        if model == Model.LocalEdit {
            imageView.image = photoModel?.img
        }else if model == Model.NetworkEdit {
            setImagesWithClosure?(photoModel?.imgUrl,imageView)
        }
        
        imageView.isUserInteractionEnabled = true
        imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap)))
        addSubview(imageView)
        if is_EditView {bringSubviewToFront(addBtn)}
        imageView.clipsToBounds = true
        if is_EditView {addDeleteBtn(imageView: imageView)}else{imageView.isHidden = true}
    }
    
    @objc func tap(tap: UITapGestureRecognizer){
        
        let imageView = tap.view as! PhotoImgView
        
        let i = imageView.index
        
        clickClosure?(i, imageView, imageView.photoModel)
    }
    
    func addDeleteBtn(imageView: UIImageView){
        let deleteBtn = UIButton(type: .custom)
        deleteBtn.setImage(UIImage(named:"SinaPhotoView.bundle/delete"), for: .normal)
        deleteBtn.frame = CGRect(x: 5, y: 5, width: 25, height: 25)
        deleteBtn.addTarget(self, action: #selector(deleteItemImageView), for: .touchUpInside)
        imageView.addSubview(deleteBtn)
    }
    
    @objc func deleteItemImageView(deleteBtn: UIButton){
        
        if is_ShowView {return}
        
        let photoImageV = deleteBtn.superview as! PhotoImgView
        
        if model == Model.LocalEdit {
            
            photoImageV.removeFromSuperview()
        }
        
        deleteBtnClosure?(photoImageV.index, photoImageV.photoModel.interfaceModel,photoImageV)
    }
    
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        if model == nil {return}
        
        if defaultWH == 0 {defaultWH = 90}
        
        cal()
        
        if count == 0 {
            self.isHidden = true;
            return
        }else{
            self.isHidden = false
            assert(model != nil, "Charlin Feng提示您: 请设置isEditView值。")
        }
    }
    
    func cal(){
        let wh: CGFloat = 90
        let colCount_Cal = colCount
        for i in (0 ..< count){
            
            weak var subView = subviews[i]
            
            let imageView = subView as? PhotoImgView
            
            imageView?.index = i
            
            let row: CGFloat = CGFloat(Int(CGFloat(i).truncatingRemainder(dividingBy: colCount_Cal)))
            let col: CGFloat = CGFloat(Int(CGFloat(i) / colCount_Cal))
            let x = row * (wh + margin)
            let y = col * (wh + margin)
            let frame = CGRect(x: x, y: y, width: wh, height: wh)
            
            UIView.animate(withDuration: 0.1) {
                subView?.frame = frame
            }
            
        }
    }
    
    
    func removeAllItems_When_NetworkEdit(){
        subviews.forEach({if $0.isKind(of: PhotoImgView.self) {$0.removeFromSuperview()}})
    }
    
}

extension CGFloat {
    
    func int_float()->CGFloat{return CGFloat(Int(self))}
    
}
